/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package helper;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

public class ConnectionHelper
{
    public static Connection GetConnection() {

        String user = null;
        String password = null;

        try {
            File file = new File("connectionInfo.xml");

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(file);

            XPathFactory xpath = XPathFactory.newInstance();
            XPath xpa = xpath.newXPath();

            String query = "/connectioninfo";
            Node node = (Node) xpa.evaluate(query, doc, XPathConstants.NODE);

            if (node != null) {
                user = node.getChildNodes().item(1).getTextContent();
                password = node.getChildNodes().item(3).getTextContent();
                System.out.print(user + "<br/>" + password);
            } else {
                System.out.print("There some problem!");
            }

        } catch (IOException ex)
        {
            System.out.print("IOException");
        }
        catch (XPathExpressionException ex)
        {
            System.out.print("XPathExpressionException");
        }
        catch (SAXException ex)
        {
            System.out.print("SAXException");
        }
        catch (ParserConfigurationException ex)
        {
            System.out.print("ParserConfigurationException");
        }

        Connection con = null;
        try {

            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=SRSDB;user="
                    + user + ";password=" + password;
            con = DriverManager.getConnection(connectionUrl);

        }
        catch (SQLException ex)
        {
            System.out.print("SQLException");
        }
        catch (ClassNotFoundException ex)
        {
            System.out.print("ClassNotFoundException");
        }
        return con;
    }
}
